package com.leilei;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lei
 * @version 1.0
 * @date 2021/4/10 21:32
 * @desc reduce 求和算子
 */
public class ReduceOperator {
    public static void main(String[] args) throws Exception {
        List<User> users = Arrays.asList(new User("张三", 12), new User("张三", 18),
                new User("李四", 22), new User("李四", 29), new User("麻子", 35));
        Map<String, List<User>> collect = users.stream().collect(Collectors.groupingBy(User::getName));
        collect.forEach((k, v) -> {
            User sumAgeUser = v.parallelStream()
                    .reduce((user, user2) -> new User(user.name, user.age + user2.age))
                    .orElse(null);
            System.out.println(sumAgeUser);
        });
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 设置并行度为1 （1个线程执行，以便观察）
        env.setParallelism(1);
        env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
        // 加载数据源
        DataStreamSource<User> stream = env.fromCollection(users);
        // 使用KeyBy算子
        KeyedStream<User, String> keyedStream = stream.keyBy(new KeySelector<User, String>() {
            @Override
            public String getKey(User value) throws Exception {
                return value.name;
            }
        });
        // 使用reduce算子
        SingleOutputStreamOperator<User> source = keyedStream.reduce(new ReduceFunction<User>() {
            @Override
            public User reduce(User value1, User value2) throws Exception {
                return new User(value1.name, value1.age + value2.age);
            }
        });
        source.print("reduce:");
        env.execute();
    }

    @NoArgsConstructor
    @AllArgsConstructor
    @Data
    @Builder
    public static class User {
        private String name;
        private Integer age;
    }

}
